$(function () {
    window.hotelConstant = {
        'photoGroupPic':8
    };
    var submitEnable = $('#requestEnable');
    var submitChange = $('#requestChange');
    var doc_enable_form = $('#doc-enable-form');
    var doc_change_form = $('#doc-change-form');
    var latitude, longtitude, originalAddress;
    var params = {};
    params.hotel = window.currentHotel;
    ajaxRequest('/Home/BookSetting/info', params, 'post', function (data) {
        doc_change_form.removeClass('hidden');
        doc_enable_form.addClass('hidden');
        if (data === undefined) {
            return;
        }
        var hotelInfo = data.data;
        var latitude = '';
        var longtitude = '';
        if(parseFloat(hotelInfo.latitude) > 0){
            latitude = hotelInfo.latitude;
            longtitude = hotelInfo.longtitude;
        }
        originalAddress = hotelInfo.address;
        var urlpic = hotelInfo.logoimageurl;
        $('#requestName').val(hotelInfo.name);
        $('#requestAddress').val(hotelInfo.address).attr({'lat':latitude,'lng':longtitude});
        $('#editAddress').val(hotelInfo.address);
        $('#doc-change-form .areaCodeValue').text(hotelInfo.areacode);
        $('#requestMobile').val(hotelInfo.mobile);
        $('#requestTelephone').val(hotelInfo.telephone);
        $('#requestContact').val(hotelInfo.contact);
        $('#requestWechat').val(hotelInfo.wechat);
        $('#requestDesc').val(hotelInfo.description);
        $('#requestOrderTime').val(hotelInfo.orderTimeout);
        $('#requestComplaint').val(hotelInfo.hotline);
        $('#pictureGroup .input-btn-group-input').val(urlpic);
        $('#pictureGroup img').attr('src',urlpic);  
        $('#requestChange').data('data-name',hotelInfo.contact);
        $('#requestChange').data('data-address',hotelInfo.address);
        $('#requestChange').data('data-mobile',hotelInfo.mobile);
        $('#requestChange').data('data-status',hotelInfo.authInfo.status);
        if(!hotelInfo.usable){
            $('#uclbrtStatus').text(lang('sealing'));
        }else if(hotelInfo.overdue){
            $('#uclbrtStatus').text(lang('Expired'));            
        }
        var templateHTML = '';
        var template = $('#templateFacility');
        for (var index in hotelInfo.facility) {
            templateHTML += createFacility(template.clone().html(), hotelInfo.facility[index].id, hotelInfo.facility[index].name, hotelInfo.facility[index].enable);
        }
        $('#requestFacilityGroup').removeClass('hidden');
        $('#requestFacility').html(templateHTML);
        componentHandler.upgradeAllRegistered();
        //认证状态
        var status = hotelInfo.authInfo.status;
        if(status == 0){
            $('.not_apply').removeClass('hidden');
        }else if(status == 1){
            $('.lost_apply').removeClass('hidden');
        }else if(status == 2){
            $('.pass_apply').removeClass('hidden');
        }else if(status == 3){
            $('.refuse_apply').removeClass('hidden');
        }else if(status == 4){
            $('.apply_expire').removeClass('hidden');
        }
    }, function (error, obj) {
        if (typeof error.responseJSON == 'undefined') {
            formInlineTip(obj, lang('tip.system'));
        } else if (error.responseJSON.status == 409) {
            doc_enable_form.removeClass('hidden');
            doc_change_form.addClass('hidden');
        } else {
            formInlineTip(obj, error.responseJSON.info);
        }
    }, submitChange);
    //申请微预定
    $('#doc-enable-form').inputValidate({
        submit: {
            query: '#requestEnable'
        },
        inputs: [{
            query: '#requestEnableName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.name'),
            emptyMessage: lang('book.nameNull')
        }, {
            query: '#requestEnableAddress',
            regexp: /^.{1,50}$/,
            message: lang('book.address'),
            emptyMessage: lang('book.addressNull')
        }, {
            query: '#requestEnableContact',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.linkman'),
            emptyMessage: lang('book.linkmanNull')
        }, {
            query: '#requestEnableMobile',
            regexp: window.commonRegexp.mobile,
            message: lang('book.mobile'),
            emptyMessage: lang('book.mobileNull')
        },{
            query: '#requestEnableDesc',
            regexp: window.commonRegexp.nameLength255,
            message: lang('book.desc'),
            emptyMessage: lang('book.descNull')
        }, {
            query: '#requestEnableOrderTime',
            regexp: /^\d{1,4}$/,
            message: lang('book.expired'),
            emptyMessage: lang('book.expiredNull')
        }]
    });
    submitEnable.on('successSubmit.amos.inputValidate', function (e) {
        e.preventDefault();
        var getLat = $('#requestEnableAddress').attr('lat');
        var getLng = $('#requestEnableAddress').attr('lng');
        var params = {};        
        params.hotel = window.currentHotel;
        params.name = $('#requestEnableName').val();
        params.description = $('#requestEnableDesc').val();
        params.address = $('#requestEnableAddress').val();
        params.longtitude = parseFloat(getLng).toFixed(6);
        params.latitude = parseFloat(getLat).toFixed(6);
        params.contact = $('#requestEnableContact').val();
        params.mobile = $('#requestEnableMobile').val();
        params.areaCode = $('#doc-enable-form .areaCodeValue').text().trim();
        params.orderTimeout = $('#requestEnableOrderTime').val();
        ajaxRequest('/Home/BookSetting/enable', params, 'post', function (data) {
            window.location.reload();
        }, null, submitEnable);
    });
    //信息修改
    $('#doc-change-form').inputValidate({
        submit: {
            query: '#requestChange'
        },
        inputs: [{
            query: '#requestName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.name'),
            emptyMessage: lang('book.nameNull')
        }, {
            query: '#requestAddress',
            regexp: /^.{1,50}$/,
            message: lang('book.address'),
            emptyMessage: lang('book.addressNull')
        }, {
            query: '#requestContact',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.linkman'),
            emptyMessage: lang('book.linkmanNull')
        }, {
            query: '#requestMobile',
            regexp: window.commonRegexp.mobile,
            message: lang('book.mobile'),
            emptyMessage: lang('book.mobileNull')
        }, {
            query: '#requestTelephone',
            regexp: window.commonRegexp.nameLength15,
            message: lang('book.proscenium'),
            required: false
        }, {
            query: '#requestWechat',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.weChat'),
            required: false
        },{
            query: '#requestDesc',
            regexp: window.commonRegexp.nameLength255,
            message: lang('book.desc'),
            emptyMessage: lang('book.descNull')
        }, {
            query: '#requestOrderTime',
            regexp: /^\d{1,4}$/,
            message: lang('book.expired'),
            emptyMessage: lang('book.expiredNull')
        }]
    });
 
    submitChange.on('successSubmit.amos.inputValidate', function (e) {
        var orderTime = $('#requestOrderTime').val();
        orderTime = parseInt(orderTime);
        if (!orderTime || orderTime <= 0 || orderTime > 1440) {
            formInlineTip($('#requestOrderTime'), lang('book.expired'));
            return;
        }
        var requestComplaint = $('#requestComplaint').val();
        if (isNaN(requestComplaint)) {
            formInlineTip($('#requestComplaint'), lang('book.hotLine'));
            return;
        }else{
            $('#requestComplaint').closest('.form-group').removeClass('has-error');
        }
        var contact = $('#requestContact').val();
        var address = $('#requestAddress').val();
        var mobile = $('#requestMobile').val();
        var getLat = $('#requestAddress').attr('lat');
        var getLng = $('#requestAddress').attr('lng');
        if(getLat == ''){
            formInlineTip($('#requestAddress'), lang('addPos'));
            return;
        }
        var params = {};
        params.hotel = window.currentHotel;
        params.name = $('#requestName').val();
        params.description = $('#requestDesc').val();
        params.address = address;
        params.longtitude = parseFloat(getLng).toFixed(6);
        params.latitude = parseFloat(getLat).toFixed(6);
        params.contact = contact;
        params.mobile = mobile;
        params.areaCode = $('#doc-change-form .areaCodeValue').text().trim();
        var telephone = $('#requestTelephone').val();
        var wechat = $('#requestWechat').val();
        if (telephone.length > 0) {
            params.telephone = telephone;
        }
        if (wechat.length > 0) {
            params.wechat = wechat;
        }
        if (requestComplaint.length > 0) {
            params.hotline = requestComplaint;
        }
        params.orderTimeout = $('#requestOrderTime').val();
        params.logoImageUrl = $('#pictureGroup img').attr('src'); 
        var facilities = [];
        $.each($('#requestFacility .checkbox-input'), function (key, item) {
            var itemObj = $(item);
            if (itemObj.prop('checked')) {
                facilities.push(itemObj.data('value'));
            }
        });
        params.facility = facilities.join(',');
        formInlineRight(submitChange);

        if(contact != $('#requestChange').data('data-name') || address != $('#requestChange').data('data-address') || mobile != $('#requestChange').data('data-mobile')){
            var isUpass = true;
        }else{
            var isUpass = false;
        }
        var status = $('#requestChange').data('data-status');
        if((isUpass && status == 1) || (isUpass && status == 2)){
            $('#presentation_Modal').modal('show');
        }else{
            ajaxRequest('/Home/BookSetting/save', params, 'post', function (data) {
                formInlineTip(submitChange, lang('successfullySave'), 2);
            }, null, submitChange);
        };
    });
    $('#pictureGroup .fileUploadTrigger').on('click',function(){
        $('#submitPicture').data('config', 'default').data('type', window.hotelConstant.photoGroupPic);
        $('#pictureSelector').trigger('click');
    });
    //申请
    $('#submitApply').on('click',function(){
        var submitBtn = $(this);
        var params = {};
        params.hotel = window.currentHotel;
        ajaxRequest('/Home/BookSetting/applyAuth', params, 'post', function (data) {
            formInlineTip(submitBtn, lang('successfullySave'), 2);
            $('.not_apply').addClass('hidden');
            $('.lost_apply').removeClass('hidden');
            $('#apply_Modal').modal('hide');
            window.location.reload();
        }, null, submitBtn);        
    });
    //重新申请
    $('#submitApplyAgain ').on('click',function(){
        var submitBtn = $(this);
        var params = {};
        params.hotel = window.currentHotel;
        ajaxRequest('/Home/BookSetting/applyAuth', params, 'post', function (data) {
            formInlineTip(submitBtn, lang('successfullySave'), 2);
            $('.apply_expire').addClass('hidden');
            $('.lost_apply').removeClass('hidden');
            $('#apply_again_Modal').modal('hide');
            window.location.reload();
        }, null, submitBtn);        
    });    
    //取消
    $('#submitApplyLost').on('click',function(){
        var submitBtn = $(this);
        var params = {};
        params.hotel = window.currentHotel;
        ajaxRequest('/Home/BookSetting/cancelAuth', params, 'post', function (data) {
            formInlineTip(submitBtn, lang('successfullySave'), 2);
            $('.not_apply').removeClass('hidden');
            $('.lost_apply').addClass('hidden');
            $('#apply_Lost_Modal').modal('hide');
            window.location.reload();
        }, null, submitBtn);        
    });   
    $('#submitPresentation').on('click',function(){
        var submitBtn = $(this);
        var requestComplaint = $('#requestComplaint').val();
        if (isNaN(requestComplaint)) {
            formInlineTip($('#requestComplaint'), lang('book.hotLine'));
            return;
        }else{
            $('#requestComplaint').closest('.form-group').removeClass('has-error');
        }
        var contact = $('#requestContact').val();
        var address = $('#requestAddress').val();
        var mobile = $('#requestMobile').val();
        var getLat = $('#requestAddress').attr('lat');
        var getLng = $('#requestAddress').attr('lng');
        if(getLat == ''){
            formInlineTip($('#requestAddress'), lang('addPos'));
            return;
        }
        var params = {};
        params.hotel = window.currentHotel;
        params.name = $('#requestName').val();
        params.description = $('#requestDesc').val();
        params.address = address;
        params.longtitude = parseFloat(getLng).toFixed(6);
        params.latitude = parseFloat(getLat).toFixed(6);
        params.contact = contact;
        params.mobile = mobile;
        params.areaCode = $('#doc-change-form  .areaCodeValue').text().trim();
        var telephone = $('#requestTelephone').val();
        var wechat = $('#requestWechat').val();
        if (telephone.length > 0) {
            params.telephone = telephone;
        }
        if (wechat.length > 0) {
            params.wechat = wechat;
        }
        if (requestComplaint.length > 0) {
            params.hotline = requestComplaint;
        }
        params.orderTimeout = $('#requestOrderTime').val();
        params.logoImageUrl = $('#pictureGroup img').attr('src'); 
        var facilities = [];
        $.each($('#requestFacility .checkbox-input'), function (key, item) {
            var itemObj = $(item);
            if (itemObj.prop('checked')) {
                facilities.push(itemObj.data('value'));
            }
        });
        params.facility = facilities.join(',');
        ajaxRequest('/Home/BookSetting/save', params, 'post', function (data) {
            formInlineTip(submitBtn, lang('successfullySave'), 2);
            $('#presentation_Modal').modal('hide');
            window.location.reload();
        }, null, submitBtn);      
    });      
});

var createFacility = function (templateHTML, id, name, enabled) {
    var template = $(templateHTML);
    template.find('.checkbox-input').attr('data-value', id).attr('checked', enabled === 1);
    template.find('.checkbox-label').html(name);
    return template.prop('outerHTML');
};
var pictureCropperSuccess = function (imageUrl, imageType) {
    var submitPicture = $('#submitPicture');
    switch (imageType) {
        case window.hotelConstant.photoGroupPic:    
            $('#pictureGroup .input-btn-group-input').val(imageUrl);
            $('#pictureGroup img').attr('src',imageUrl);   
            $('#pictureModal').modal('hide');
            break;
        default:
            break;
    }
};
$(function () {
    var picture = $('#picturePreview');
    var submitPicture = $('#submitPicture');
    var submitPictureModal = $('#pictureModal');
    picture.cropper({
        aspectRatio: 1,
        viewMode: 1
    });

    $('#pictureSelector').on('change', function (e) {
        var input = $(this);
        var files = !!input[0].files ? input[0].files : [];
        if (!files.length) {
            return;
        }
        var file = files[0];
        if (!window.FileReader) {
            window.alert(lang('photograph.1'));
            return;
        }
        if (file.size > 5242880) {
            window.alert(lang('photograph.2'));
            return;
        }
        if (!/^image/.test(file.type)) {
            window.alert(lang('photograph.3'));
            return;
        }

        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function (e) {
            picture.attr('src', this.result);
            input.val('');
            submitPictureModal.modal('show');
        };
    });
    submitPictureModal.on('shown.bs.modal', function () {
        formInlineRight(submitPicture);
        picture.cropper('replace', picture.attr('src'));
    });

    var defaultSuccessHandler = function (data) {
        submitPicture.removeAttr('disabled');
        return data.data.filename;
    };

    submitPicture.on('click', function (e) {
        e.preventDefault();

        picture.cropper('getCroppedCanvas', {
            width: 700,
            height: 393.75
        }).toBlob(function (blob) {
            if (blob.size > 3145728) {
                formInlineTip(submitPicture, lang('photograph.4'));
                return;
            }

            if (submitPicture.attr('disabled') !== undefined) {
                return;
            }
            submitPicture.attr('disabled', true);
            var config = submitPicture.data('config');
            var imageType = submitPicture.data('type');
            var formData = new FormData();
            formData.append('file', blob, 'blob.jpeg');
            formData.append('config', config);
            formData.append('hotel', window.currentHotel);
            $.ajax('/Home/File/upload', {
                method: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    var imageUrl = defaultSuccessHandler(data);
                    pictureCropperSuccess(imageUrl, imageType);

                },
                error: function (error) {
                    submitPicture.removeAttr('disabled');
                    if (error.responseJSON === undefined) {
                        formInlineTip(submitPicture, lang('tip.system'));
                    } else {
                        formInlineTip(submitPicture, error.responseJSON.info + (error.responseJSON.data ? ',' + error.responseJSON.data : ''));
                    }
                }
            });
        }, 'image/jpeg');
    });
    //地址
    window.map = false;
    window.isBook = false;
    var getposition = function(getLat,getLng,type){
        if(window.map == false){
            var map = new BMap.Map("allmap");        
            window.map = map;
        };
        var map = window.map;
        map.clearOverlays();
        var myGeo = new BMap.Geocoder();
        var navigationControl = new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_LARGE,
            enableGeolocation: true
        });
        if(getLat !== ''){
            window.lat = getLat;
            window.lng = getLng;
            var point = new BMap.Point(getLng, getLat);
            map.centerAndZoom(point, 16);
            map.addControl(navigationControl); 
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
            map.enableScrollWheelZoom(true);
            map.panBy(291,230);
            marker.enableDragging();
            marker.addEventListener("dragend", function(e){
                window.lng = e.point.lng;
                window.lat = e.point.lat;
            });
        }else{
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function(r){
                if(this.getStatus() == BMAP_STATUS_SUCCESS){
                    window.lat = r.point.lat;
                    window.lng = r.point.lng;
                    map.centerAndZoom(r.point, 16);
                    map.addControl(navigationControl); 
                    var marker = new BMap.Marker(r.point);
                    map.addOverlay(marker);
                    map.panBy(291,230);
                    marker.enableDragging();
                    marker.addEventListener("dragend", function(e){
                        window.lng = e.point.lng;
                        window.lat = e.point.lat;
                    });
                }    
            },{enableHighAccuracy: true});             
        }    
        if(type == 2){
            window.isBook = true;
        };
    };
    $('#edit-address').on('click',function(){
        var getLat = $('#requestAddress').attr('lat');
        var getLng = $('#requestAddress').attr('lng');
        getposition(getLat,getLng,2);
    });
    $('#edit-enableAddress').on('click',function(){
        var getLat = $('#requestEnableAddress').attr('lat');
        var getLng = $('#requestEnableAddress').attr('lng');
        getposition(getLat,getLng,1);
    });
    $('#submitPostion').on('click',function(){
        var address = $('#editAddress').val();
        if(window.isBook){
            $('#requestAddress').val(address).attr({'lat':window.lat,'lng':window.lng});
        }else{
            $('#requestEnableAddress').val(address).attr({'lat':window.lat,'lng':window.lng});
        }
        $('#editAddressModal').modal('hide');
        $('.form-group').removeClass('has-error')
    });
});